import logging
import util.dtest
import test.utils
import test.neon_support as ns

print '''Test of N nodes, each sending a small amount of data between
them using TCP.'''

N = 5

dtest = util.dtest.DTest()
cond = ns.Conditions(dtest)

def node_name(i):
    return 'node-%d' % i

for i in xrange(N):
    dtest.add_node(ns.NeonNode(node_name(i)))

# Connectivity matrix horz -- tcp out, vert -- tcp in
#    0  1  2  3  4
M =[[0, 1, 0, 1, 0], # 0
    [0, 0, 1, 1, 0], # 1 
    [0, 0, 0, 0, 1], # 2
    [0, 0, 1, 0, 0], # 3
    [1, 0, 0, 0, 0]] # 4

# just to check that we don't have a double link
for i in xrange(N):
    for j in xrange(N):
        assert M[i][j] + M[j][i] != 2, 'double link i, j = %d,%d' % (i,j)

# create listening interfaces
tcp_in = {}
for i in xrange(N):
    tcp_in[i] = dtest.node(node_name(i)).reg_tx_tcp_in()

# create connections
for i in xrange(N):
    for j in xrange(N):
        if M[i][j] == 1:
            dtest.node(node_name(j)).reg_tx_tcp_out(tcp_in[i], 1)

# finish configuration
dtest.set_mapper(util.dtest.LocalMapper())
dtest.configure()
dtest.setup_files()

def test_script(tr):
    for i in xrange(N):
        dtest.node(node_name(i)).run_tx()
    tr.wait_for(5, cond.on_all(cond.tx_is_running))

    api_sock = {}
    for i in xrange(N):
        api_sock[i] = dtest.node(node_name(i)).tx_api_sock()

    for i in xrange(N):
        for j in xrange(N):
            if M[i][j] == 0:
                continue
            tr.wait_for(5, cond.channel_state,
                        node_name(i), '*', node_name(j), 'handshake')
            
    # XXX/bowei -- waste of time? implement more when we need routing
    
dtest.run(test_script)
